<script lang="ts" setup>
import { h, ref } from 'vue';
import { NButton, NSwitch, useMessage } from 'naive-ui';
import type { DataTableColumns } from 'naive-ui';
type Song = {
  no: number;
  title: string;
  length: string;
  status: boolean;
};
// 全选
const checkedRowKeys = ref<any[]>([]);

const data = ref([
  { id: 1, word: '狗', sense_type: '政治', sense_user: 'xxx', status: 0, date: '2024-01-01' },
  { id: 2, word: '傻', sense_type: '其他', sense_user: 'xxx', status: 1, date: '2024-01-01' },
  { id: 3, word: '222', sense_type: '政治', sense_user: 'xxx', status: 0, date: '2024-01-01' }
]);
const createColumns = ({
  play,
  editform,
  toggleStatus
}: {
  play: (row: Song) => void;
  editform: (row: Song) => void;
  toggleStatus: (row: Song) => void;
}): DataTableColumns<Song> => {
  return [
    {
      type: 'selection',
      width: 10
    },
    {
      title: 'ID',
      key: 'id',
      align: 'center',
      minWidth: 10,
      maxWidth: 100
    },
    {
      title: '敏感词',
      key: 'word',
      align: 'center',
      resizable: true
    },
    {
      title: '类型',
      key: 'sense_type',
      align: 'center',
      resizable: true,
      minWidth: 100,
      maxWidth: 500
    },
    {
      title: '创建者',
      key: 'sense_user',
      align: 'center',
      resizable: true,
      minWidth: 100,
      maxWidth: 500
    },
    {
      title: '是否启用',
      key: 'status',
      align: 'center',
      resizable: true,
      render(row) {
        return h(
          NSwitch,
          {
            value: row.status,
            onClick: () => toggleStatus(row)
          },
          {}
        );
      }
    },
    {
      title: '创建时间',
      key: 'date',
      align: 'center',
      resizable: true,
      minWidth: 100,
      maxWidth: 500
    },
    {
      title: '操作',
      key: 'actions',
      render(row) {
        return h('div', { style: { display: 'flex', gap: '8px' } }, [
          h(
            'a',
            {
              style: { textDecoration: 'none', color: 'blue', cursor: 'pointer' },
              strong: true,
              tertiary: true,
              size: 'small',
              onClick: () => editform(row)
            },
            { default: () => '编辑' }
          ),
          h(
            'a',
            {
              style: { textDecoration: 'none', color: 'blue', cursor: 'pointer' },
              strong: true,
              colorScheme: 'error',
              tertiary: true,
              size: 'small',
              onClick: () => play(row)
            },
            { default: () => '删除' }
          )
        ]);
      }
    }
  ];
};

const message = useMessage();
const visible = ref<boolean>(false);
const type = ref<string>('');
const title = ref('新增');
// const originalData = ref<Song | null>(null); // 用于存储原始数据的副本
// 表单数据
const formRef = ref<any>(null);
const model = ref<any>({
  word: '',
  sense_type: '其他',
  status: 0,
  sense_user: '工商银行',
  date: new Date()
});
const rules = ref({
  // word: {
  //   required: true,
  //   trigger: 'blur',
  //   message: '请输入敏感词',
  // },
  // sense_type: {
  //   required: true,
  //   trigger: 'blur',
  //   message: '请选择敏感词类型',
  // },
});
// 敏感词
const wordOptions = ref<any>([
  { value: 1, label: '其他' },
  { value: 2, label: '反动' },
  { value: 3, label: '政治' },
  { value: 4, label: '敏感' },
  { value: 5, label: '暴恐' },
  { value: 6, label: '毒品' },
  { value: 7, label: '社会' },
  { value: 8, label: '色情' },
  { value: 9, label: '赌博' }
]);
const handleButtonClick = (key: any) => {
  console.log(key, 'key');
  switch (key) {
    case 'addApi':
      title.value = '新增敏感词';
      model.value.sense_type = '其他';
      model.value.word = '';
      break;
    case 'editApi':
      title.value = '编辑敏感词';
      break;
    default:
      break;
  }
  type.value = key;
  visible.value = true;
};
// 重置表单
const reset = () => {
  model.value = {
    word: '',
    sense_type: '其他'
  };
};
// 关闭
const closeDrawer = () => {
  model.value = {
    word: '',
    sense_type: '其他',
    status: 0
  };
  visible.value = false;
};

const handleSubmit = (e: any) => {
  e.preventDefault();
  switch (type.value) {
    case 'addApi':
      message.success('添加成功');
      break;
    case 'editApi':
      message.success('编辑成功');
      break;
    default:
      message.error('未知操作');
      break;
  }

  closeDrawer();
};

// 定义分页配置的接口类型
interface PaginationConfig {
  pageSize: number;
  page: number;
  // currentPage: number;
}

const pagination = ref<PaginationConfig>({
  pageSize: 10,
  page: 1 // 总页数，根据实际数据计算
  // currepagetPage: 1, // 当前页码
});
const play = () => {
  console.log('触发删除');
};
const editform = (row: Song) => {
  console.log(row, '编辑');
  // 在编辑前存储当前行数据的副本
  model.value = row;
  handleButtonClick('editApi');
};

const toggleStatus = async (row: Song) => {
  row.status = !row.status;
  console.log(row.status ? '开关打开' : '开关关闭', '状态已更新');
};
const columns = createColumns({ play, toggleStatus, editform });
// 分页
const handlePageChange = (newPage: number) => {
  console.log(`第${newPage}页`);

  pagination.value.page = newPage;
  // 在这里调用获取数据的函数，例如 fetchData(page.value, pageSize.value);
};

const handlePageSizeChange = (newPageSize: number) => {
  console.log(`一页${newPageSize}条`);
  pagination.value.pageSize = newPageSize;
  // 在这里调用获取数据的函数，例如 fetchData(page.value, pageSize.value);
};
// 全选反选
const handleCheck = (rowKeys: any) => {
  console.log('rowKeys :', rowKeys, 'checkedRowKeys :', checkedRowKeys.value);

  checkedRowKeys.value = rowKeys;
};
const handleAlldel = async () => {
  try {
    // 准备要删除的数据的 ID 数组
    const idsToDelete = checkedRowKeys.value;
    // 如果没有选中的项，则不执行删除
    if (idsToDelete.length === 0) {
      message.warning('请先选择要删除的项');
      return;
    }

    // 调用 API 进行批量删除
    // const response = await axios.post(apiDeleteUrl, { ids: idsToDelete });

    // 假设服务器返回了被删除的数据的 ID 数组
    // const deletedIds = response.data;
    // 从 data 和 checkedRowKeys 中移除已删除的数据
    // data.value = data.value.filter(item => !deletedIds.includes(item.id));
    checkedRowKeys.value = [];
    message.success('删除成功');
  } catch (error) {
    console.error('删除失败:', error);
    message.error('删除失败');
  }
};
</script>

<template>
  <div>
    <NCard>
      <div class="m-10px w-100% flex" style="justify-content: space-between">
        <NSpace justify="space-between">
          <NButton type="info" @click="handleButtonClick('addApi')">新增</NButton>
          <NButton type="info">禁用</NButton>
          <NButton type="info">启用</NButton>
          <NButton type="info" @click="handleAlldel">删除</NButton>
        </NSpace>
        <NSpace size="small">
          <NInput placeholder="搜索" clearable class="w-250px"></NInput>
        </NSpace>
      </div>
      <NDataTable
        v-model:checked-row-keys="checkedRowKeys"
        :row-key="row => row.id"
        :columns="columns"
        :data="data"
        :bordered="false"
        @update:checked-row-keys="handleCheck"
      />
      <NPagination
        v-model:page="pagination.page"
        v-model:page-size="pagination.pageSize"
        :page-count="100"
        show-size-picker
        :page-sizes="[10, 20, 30, 40]"
        @update:page="handlePageChange"
        @update:page-size="handlePageSizeChange"
      />
    </NCard>
    <NDrawer
      v-model:show="visible"
      display-directive="show"
      :width="360"
      :on-mask-click="
        () => {
          visible = true;
        }
      "
    >
      <NDrawerContent :title="title" :native-scrollbar="false" closable>
        <NForm ref="formRef" :model="model" :rules="rules">
          <NFormItem label="敏感词" path="word">
            <NInput v-model:value="model.word" placeholder="请输入敏感词" />
          </NFormItem>

          <NFormItem label="敏感词类型" path="sense_type">
            <NSelect v-model:value="model.sense_type" :options="wordOptions" placeholder="请选择" />
          </NFormItem>
        </NForm>
        <template #footer>
          <NSpace :size="16">
            <NButton @click="reset">重置</NButton>
            <NButton type="primary" @click="handleSubmit">确定</NButton>
          </NSpace>
        </template>
      </NDrawerContent>
    </NDrawer>
  </div>
</template>

<style scoped></style>
